﻿using System;
using ProjectDanmaku.Entity;
using ProjectDanmaku.Entity.Manipulator;
using ProjectDanmaku.Util;
using UnityEngine;

namespace ProjectDanmaku.Avatar.Reimu
{
    public class ReimuCardEntityData : EntityData
    {
        
    }
    
    public class ReimuCardBulletLayer : EntitySubLayer
    {
        [SerializeField] private AudioSource bulletDamageAudioSource;
        [SerializeField] private AudioClip bulletDamageAudioClip;
        
        [SerializeField] private Sprite cardSprite;
        [SerializeField] private GameObject deadCardPrefab;
        
        private Mesh _mesh;
        
        private SimpleMotionManipulator _simpleMotionManipulator = new();
        private ScreenBoundCheckManipulator _screenBoundCheckManipulator = new();
        private ShootableCollidePhysicsManipulator _shootablePhysicsManipulator = new();
        
        private float _lastSoundPlayTime;

        private void OnEnable()
        {
            _shootablePhysicsManipulator.OnHitCallback += OnHit;
        }

        private void OnDisable()
        {
            _shootablePhysicsManipulator.OnHitCallback -= OnHit;
        }

        private void OnDestroy()
        {
            DestroyImmediate(_mesh, true);
        }

        protected override void Awake()
        {
            base.Awake();

            _mesh = MeshUtility.SpriteToMesh(cardSprite);
            ApplySpriteToMaterial(cardSprite);
        }

        private void PlayHitSound()
        {
            if (Time.time - _lastSoundPlayTime > 0.05f)
            {
                bulletDamageAudioSource.clip = bulletDamageAudioClip;
                bulletDamageAudioSource.Play();
                _lastSoundPlayTime = Time.time;
            }
        }

        private void OnHit(EntityData data)
        {
            PlayHitSound();
            
            Destroy(
                Instantiate(
                    deadCardPrefab, data.Position, Quaternion.Euler(0, 0, data.RotateZ * Mathf.Rad2Deg)), 1f);
        }

        public override Type GetEntityDataType()
        {
            return typeof(ReimuCardEntityData);
        }

        public override Mesh GetSpriteMesh()
        {
            return _mesh;
        }

        protected override void EntityLogicTick(EntityData data)
        {
            _simpleMotionManipulator.Do(data);
            _screenBoundCheckManipulator.Do(data);
        }

        protected override void EntityPhysicsTick(EntityData data)
        {
            _shootablePhysicsManipulator.Do(data);
        }

        protected override void EntityLateTick(EntityData data)
        {
            
        }

        protected override void EntityInit(EntityData data)
        {
            
        }
    }
}